package com.heima.article.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author: itheima
 * @create: 2022-01-20 11:58
 */
@Slf4j
@Service
public class UpDownListener {


    @Autowired
    private IApArticleService apArticleService;


    /**
     * 监听上下架话题 完成发表文章上下架
     *
     * @param record
     */
    @KafkaListener(topics = "${topic.upDownTopic}")
    public void handlerMessage(ConsumerRecord<String, String> record) {
        try {
            log.info("[文章微服务]文章上下架");
            if (StringUtils.isNotBlank(record.value())) {
                HashMap map = JSON.parseObject(record.value(), HashMap.class);
                Long articleId = (Long) map.get("articleId");
                Boolean isDown = (Boolean) map.get("isDown");

                //更新发布文章状态
                LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(ApArticle::getId, articleId);
                updateWrapper.set(ApArticle::getIsDown, isDown);
                apArticleService.update(updateWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章上下架异常：{}，异常信息：{}", record.value(), e.getMessage());
        }
    }
}
